package com.client.lu;

import java.io.IOException;
import java.io.StringReader;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;

import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;

import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;

import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

import com.client.lucene.ik.IKAnalyzer6y;

public class AnalyzerTest {

	
	
	
	
	public String printAnalyzer(String msg) throws Exception {
		
		String word = null;
		Analyzer analyzer = new IKAnalyzer6y();
		
		
		// 将字符串转化成流对象
		StringReader reader = new StringReader(msg);
		// analyzer的实现,是通过底层tokenStream流实现的,这个流的作用
		// 就是将源数据流转化,计算,称为词项流的对象,可以获取很多词项相关的内容;
		
		TokenStream tokenStream = analyzer.tokenStream("test", reader);
		
		tokenStream.reset();
		
		// 从tokenStream中获取词项结果,打印
		CharTermAttribute attribute = tokenStream.getAttribute(CharTermAttribute.class);
		while (tokenStream.incrementToken()) {
			String ms = attribute.toString();

			Path indexPath = Paths.get("index");
			Directory dir = FSDirectory.open(indexPath);

			// 输入流
			IndexReader reader1 = DirectoryReader.open(dir);
			// 通过输入流构造查询对象
			IndexSearcher searcher = new IndexSearcher(reader1);
			// 封装查询的条件,根据不同的情况,每次查询的条件未必一致
		    Term term = new Term("content", ms);
			//QueryParser parser=new Query();
			Query query = new TermQuery(term);

			// 调用方法获取查询结果
			TopDocs docs = searcher.search(query, 10);// 10表示查询的结果集最大数量
			// 获取真正的document对象,
			ScoreDoc[] scoreDocs = docs.scoreDocs;// 每个document都具有默认评分数字
			
            if (scoreDocs.length > 0) {
				
			word=ms;
                 
			}


		}
		return word;
		
	}

	

}
